import pDown from '@/images/common/down1.png';
import utils from '@/utils';
import { ScrollView, View, Image, Text } from '@tarojs/components';
import React, { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { AtFloatLayout } from 'taro-ui';
import { connect } from 'react-redux';
import Imagelocation from '@/components/Imagelocation';
import pStar from '@/mainSubPack/images/takeOut/star.png';
import './index.scss';

const Delivery = ({ dispatch, isOpened, onClose, curShopId, handleAddr }) => {
  const [shopList, setShopList] = useState([]);
  const [curLocation, setCurLocation] = useState(null);

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        timeout: 5000,
        success: (res) => {
          const { latitude, longitude } = res;
          const timeStamp = new Date().getTime();
          setCurLocation({ latitude, longitude });
          utils.setLocalStorage('location', { latitude, longitude, timeStamp });
        },
        fail: () => {
          Taro.showToast({
            title: '请开启定位权限',
            icon: 'none',
            mask: false,
            duration: 2000,
          });
        },
      });
    }
  };

  const getShopList = () => {
    dispatch({
      type: 'takeOut/getActivityOrgListModel',
      payload: {
        page: 1,
        pageSize: 11,
        lat: curLocation.latitude,
        lon: curLocation.longitude,
        industryType: 2,
      },
    }).then((ret) => {
      let list = [];
      if (ret.list && ret.list.length > 0) {
        list = [...ret.list];
      }
      let effectList = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i].id != curShopId && list[i].deliveryMoney != '-1') {
          effectList.push({ ...list[i] });
        }
      }
      setShopList(effectList);
    });
  };

  useEffect(() => {
    getLocation();
  }, []);

  useEffect(() => {
    isOpened && curLocation && shopList.length == 0 && getShopList();
  }, [isOpened, curLocation]);

  const goShopDetail = (shopId, merchantId) => {
    let url =
      '/mainSubPack/takeOutShop/index' + '?' + 'orgId=' + shopId + '&merchantId=' + merchantId;
    Taro.navigateTo({
      url,
    });
  };

  return (
    <View className="takeOutDelivery" catchMove>
      <AtFloatLayout isOpened={isOpened} onClose={onClose}>
        <View className="head flex-column-center-center">
          <View className="iconArea flex-row-center-center" onClick={onClose}>
            <Image className="downicon" src={pDown} />
          </View>
          <View className="title txt28 bold">本店超出配送范围</View>
          <View className="tip txt24 gray">更换地址再下单</View>
          <View
            className="addrBtn txt24 customePageBorderStyle customePageStyle flex-row-center-center"
            onClick={() => {
              onClose();
              handleAddr(true);
            }}
          >
            更换地址
          </View>
        </View>

        <View className={'label flex-row-center-center ' + (shopList.length > 0 ? '' : 'hidden')}>
          <View className="line"></View>
          <View className="adjust txt20 gray">为你推荐附近相似好店</View>
          <View className="line"></View>
        </View>

        <ScrollView scrollY className="shop-list">
          {shopList.length > 0 &&
            shopList.map((shop, index) => {
              return (
                <View
                  className="shop"
                  key={index}
                  onClick={() => goShopDetail(shop.id, shop.merchantId)}
                >
                  <View className="left">
                    <Imagelocation className="shopIcon" src={shop.logo} type="shop" />
                  </View>
                  <View className="right">
                    <View className="name">{shop.name}</View>
                    <View className="info">
                      <View className="infoLeft">
                        <Image
                          className="starIcon"
                          src={typeof shop.grade !== 'undefined' ? pStar : ''}
                        />
                        <Text className="starNum customePageStyle">{shop.grade || ''}</Text>
                        <Text className="saleTitle">
                          {typeof shop.grade !== 'undefined' ? '月售' : ''}
                        </Text>
                        <Text className="saleNum">
                          {typeof shop.saleNum !== 'undefined' ? shop.saleNum : ''}
                        </Text>
                      </View>
                      <View className="infoRight">
                        <Text className="sendTime">
                          {typeof shop.sendTime !== 'undefined' ? shop.sendTime + '分钟' : ''}
                        </Text>
                        <Text className="distance">
                          {typeof shop.distance !== 'undefined' ? shop.distance + 'km' : ''}
                        </Text>
                      </View>
                    </View>
                    <View className="fee">
                      <Text className="mText">
                        {typeof shop.minMoney !== 'undefined' ? '起送¥' + shop.minMoney : ''}
                      </Text>
                      <Text className="mText">
                        {typeof shop.deliveryMoney !== 'undefined'
                          ? shop.deliveryMoney == 0
                            ? '免配送费'
                            : shop.deliveryMoney == -1
                            ? '超出配送范围'
                            : '配送费¥' + shop.deliveryMoney
                          : ''}
                      </Text>
                      <Text className="mText">
                        {typeof shop.peopleAvg !== 'undefined' ? '人均¥' + shop.peopleAvg : ''}
                      </Text>
                    </View>
                    {shop.policy && shop.policy.length > 0 && (
                      <View className="manjianLine">
                        {shop.policy.map((item, idx) => (
                          <Text
                            className="manjian customePageStyle customePageBackgroundStyle"
                            key={'manjian' + idx}
                          >
                            {item}
                          </Text>
                        ))}
                      </View>
                    )}
                  </View>
                </View>
              );
            })}
        </ScrollView>
      </AtFloatLayout>
    </View>
  );
};

export default connect(({}) => ({}))(Delivery);
